package com.cskaoyan.service;

import com.cskaoyan.bean.admin.order.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.wx.order.bo.OrderCommentBo;
import com.cskaoyan.bean.wx.order.bo.SubmitOrderBo;
import com.cskaoyan.bean.wx.order.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.Constant;
import com.cskaoyan.util.ShiroUtil;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cskaoyan.bean.wx.user.UserIndexVo;
import com.cskaoyan.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wangzhenyu
 * @since 2022/11/19 21:49
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCommentMapper commentMapper;


    @Override
    public OrderListWithPageVo orderList(BasePageInfo info, Date start, Date end, Short[] orderStatusArray, String orderSn, Integer userId, Date[] timeArray) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        // 排序
        example.setOrderByClause("update_time" + " " + info.getOrder());
        MarketOrderExample.Criteria criteria = example.createCriteria();
        if (start != null) {
            criteria.andAddTimeGreaterThanOrEqualTo(start);
        }
        if (end != null) {
            criteria.andAddTimeLessThanOrEqualTo(end);
        }
        if (orderStatusArray != null && orderStatusArray.length > 0) {
            criteria.andOrderStatusIn(Arrays.asList(orderStatusArray));
        }
        if (!StringUtil.isEmpty(orderSn)) {
            criteria.andOrderSnLike("%" + orderSn + "%");
        }
        if (userId != null && userId > 0) {
            criteria.andUserIdEqualTo(userId);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(marketOrders);
        int pages = pageInfo.getPages();
        Integer total = (int) pageInfo.getTotal();
        ArrayList<OrderListVo> orderListVos = new ArrayList<>();
        for (MarketOrder order : marketOrders) {
            OrderListVo orderListVo = new OrderListVo(order.getId(), order.getUserId(), order.getOrderSn(), order.getOrderStatus(), order.getAftersaleStatus(), order.getConsignee(),
                    order.getMobile(), order.getAddress(), order.getMessage(), order.getGoodsPrice(), order.getFreightPrice(), order.getCouponPrice(), order.getIntegralPrice(), order.getGrouponPrice(), order.getOrderPrice(), order.getActualPrice(), order.getShipSn(), order.getShipChannel(), order.getShipTime(), order.getConfirmTime(), order.getComments(), order.getAddTime(), order.getUpdateTime(), order.getDeleted());
            orderListVos.add(orderListVo);
        }
        OrderListWithPageVo orderListWithPageVo = new OrderListWithPageVo(total, pages, info.getLimit(), info.getPage(), orderListVos);
        return orderListWithPageVo;
    }

    @Override
    public OrderDetailVo queryOrderDetail(Integer id) {
        // 获取订单信息
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(id);
        if (marketOrder.getDeleted()) {
            return null;
        }
        // MarketOrderExample example = new MarketOrderExample();
        // List<MarketOrder> marketOrders = orderMapper.selectByExample(example);
        // 获取订单中的商品信息
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderCriteria = marketOrderGoodsExample.createCriteria();
        if (id != null && id > 0) {
            orderCriteria.andOrderIdEqualTo(id);
        }
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
        // 获取订单中的用户信息
        MarketUser marketUser = userMapper.selectByPrimaryKey(marketOrder.getUserId());
        UserInOrderDetail user = new UserInOrderDetail(marketUser.getNickname(), marketUser.getAvatar());
        OrderDetailVo orderDetailVo = new OrderDetailVo(marketOrderGoods, user, marketOrder);
        return orderDetailVo;
    }

    @Override
    public void orderRefund(Integer orderId, BigDecimal refund) {
        MarketOrder marketOrder = new MarketOrder();
        Date date = new Date();
        marketOrder.setUpdateTime(date);
        marketOrder.setRefundTime(date);
        marketOrder.setOrderStatus((short) 203);
        marketOrder.setAftersaleStatus((short) 3);
        // marketOrder.setRefundType("微信退款");
        marketOrder.setRefundAmount(refund);
        marketOrder.setId(orderId);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void orderShip(Integer orderId, String shipChannel, String shipSn) {
        MarketOrder marketOrder = new MarketOrder();
        Date date = new Date();
        marketOrder.setUpdateTime(date);
        marketOrder.setId(orderId);
        marketOrder.setShipChannel(shipChannel);
        marketOrder.setShipSn(shipSn);
        marketOrder.setShipTime(date);
        marketOrder.setOrderStatus((short) 301);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    // 快递公司直接写死
    @Override
    public List<CourierVo> getOrderChannel() {
        ArrayList<CourierVo> courierVos = new ArrayList<>();
        courierVos.add(new CourierVo("ZTO", "中通快递"));
        courierVos.add(new CourierVo("YTO", "圆通速递"));
        courierVos.add(new CourierVo("YD", "韵达快递"));
        courierVos.add(new CourierVo("YZPY", "邮政快递包裹"));
        courierVos.add(new CourierVo("EMS", "EMS"));
        courierVos.add(new CourierVo("DBL", "德邦快递"));
        courierVos.add(new CourierVo("FAST", "快捷快递"));
        courierVos.add(new CourierVo("ZJS", "宅急送"));
        courierVos.add(new CourierVo("TNT", "TNT快递"));
        courierVos.add(new CourierVo("UPS", "UPS"));
        courierVos.add(new CourierVo("DHL", "DHL"));
        courierVos.add(new CourierVo("FEDEX", "FEDEX联邦（国内件）"));
        courierVos.add(new CourierVo("FEDEX_GJ", "FEDEX联邦（国外件）"));
        return courierVos;
    }

    //{"errno":623,"errmsg":"订单不能删除"}
    @Override
    public Integer deleteOrder(Integer orderId) {
        MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (order.getDeleted()) {
            return 623;
        }
        // 逻辑删除订单表
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(true);
        Date date = new Date();
        marketOrder.setUpdateTime(date);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
        // 逻辑删除订单商品表
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setUpdateTime(date);
        marketOrderGoods.setDeleted(true);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        orderGoodsMapper.updateByExampleSelective(marketOrderGoods, marketOrderGoodsExample);
        return 200;
    }

    /**
     * 微信小程序获取订单列表
     *
     * @param basePageInfo
     * @param showType
     * @return
     */
    @Override
    public CommonData getOrderList(BasePageInfo basePageInfo, Integer showType, Integer userId) {
        // 前台页面不是按页显示，是按滑轮滚动显示,还是按照原来分页使用
        // showType ：1--待付款，2--待发货，3--待收货，4--待评价，0--全部
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        // 设置排序
        example.setOrderByClause("add_time desc");
        MarketOrderExample.Criteria criteria = example.createCriteria();
        if (userId != null && userId > 0) {
            criteria.andUserIdEqualTo(userId);
        }
        if (showType > 0) {
            // 把接收的showType转换成对应的订单状态然后查找
            myAndShowTypeSearch(criteria, showType);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);
        // 获取订单列表（自定义方法）
        LinkedList<WxOrderListVo> wxOrderListVos = getOrders(marketOrders);
        PageInfo<WxOrderListVo> wxOrderListVoPageInfo = new PageInfo<>(wxOrderListVos);
        return CommonData.data(wxOrderListVoPageInfo);
    }

    private void myAndShowTypeSearch(MarketOrderExample.Criteria criteria, Integer showType) {
        // todo showType ：1--待付款，2--待发货，3--待收货，4--待评价，0--全部
        if (showType == 1) {
            criteria.andOrderStatusEqualTo((Short.valueOf("101")));
        } else if (showType == 2) {
            criteria.andOrderStatusEqualTo((Short.valueOf("201")));
        } else if (showType == 3) {
            criteria.andOrderStatusEqualTo((Short.valueOf("301")));
        } else if (showType == 4) {
            LinkedList<Short> shorts = new LinkedList<>();
            shorts.add((Short.valueOf("401")));
            shorts.add((Short.valueOf("402")));
            criteria.andOrderStatusIn(shorts);
        }
    }

    @Override
    public WxOrderDetailVo getWxOrderDetail(Integer orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        WxOrderInfoOfWxOrderDetailVo orderInfo = getOrderInfo(marketOrder);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
        //List<WxOrderGoodsOfWxOrderDetailVo> orderGoodsOfWxOrderDetailVoList = getWxOrderGoodsInfoInWxOrderDetail(marketOrderGoods);
        return new WxOrderDetailVo(new ArrayList(),orderInfo,marketOrderGoods);
    }

    // {"cartId":49,"addressId":10,"couponId":2,"userCouponId":33,"message":"测试用例","grouponRulesId":0,"grouponLinkId":0}
    /**
     * 提交订单
     * @param submitOrderBo 接收购物车id，地址id，优惠劵id，todo ，订单留言，团购规则ID，关联market_groupon_rules表ID字段，如果是开团用户，则groupon_id是0；如果是参团用户，则groupon_id是团购活动ID
     * @return
     */
    @Override
    public MarketOrder submitOrder(SubmitOrderBo submitOrderBo, Integer userId) {
        // todo 先查找对应的表取得对应数据，然后插入到订单表中
        MarketAddress marketAddress = addressMapper.selectByPrimaryKey(submitOrderBo.getAddressId());
        String consignee = marketAddress.getName();
        String mobile = marketAddress.getTel();
        String address = marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getCounty() + marketAddress.getAddressDetail();
        // todo 获取商品总费用
        // 取session域中购物车数据
        BigDecimal goodsPrice = BigDecimal.ZERO;
        // MarketCart marketCart = null;
        List<MarketCart> marketCarts = new LinkedList<>();
        if (submitOrderBo.getCartId() == 0) {
            // 0:查选中的商品
            Double aDouble = cartMapper.selectCheckedGoodsAmount(userId);
            if (aDouble == null) {
                return null;
            }
            goodsPrice = BigDecimal.valueOf(aDouble);
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andCheckedEqualTo(true);
            criteria.andDeletedEqualTo(false);
            marketCarts = cartMapper.selectByExample(marketCartExample);

            // 逻辑删除
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            cartMapper.updateByExampleSelective(marketCart, marketCartExample);
        } else if (submitOrderBo.getCartId() == -1){
            // 直接购买
            // 从session域中获取marketCart对象
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            Object fastAdd = session.getAttribute("fastAdd");
            MarketCart marketCart = null;
            if (fastAdd instanceof MarketCart) {
                marketCart = (MarketCart) fastAdd;
            } else {
                return null;
            }
            // MarketCart marketCart = cartMapper.selectByPrimaryKey(submitOrderBo.getCartId());
            goodsPrice = marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber()));
            marketCarts.add(marketCart);
        }
        // 配送费用
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        MarketSystemExample.Criteria criteria = marketSystemExample.createCriteria();
        criteria.andKeyNameLike("market_express_freight%");
        List<MarketSystem> marketSystems = systemMapper.selectByExample(marketSystemExample);
        String marketExpressFreightMin = null;
        String marketExpressFreightValue = null;
        for (MarketSystem marketSystem : marketSystems) {
            if ("market_express_freight_min".equals(marketSystem.getKeyName())) {
                marketExpressFreightMin = marketSystem.getKeyValue();
            }
            if ("market_express_freight_value".equals(marketSystem.getKeyName())) {
                marketExpressFreightValue = marketSystem.getKeyValue();
            }
        }
        BigDecimal freightPrice = BigDecimal.ZERO;
        if (goodsPrice.compareTo(new BigDecimal(marketExpressFreightMin)) == -1) {
            // 不包邮
            freightPrice = new BigDecimal(marketExpressFreightValue);
        }
        // 获取优惠金额
        BigDecimal couponPrice = BigDecimal.ZERO;
        if (submitOrderBo.getCouponId() != -1 && submitOrderBo.getCouponId() != 0) {
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(submitOrderBo.getCouponId());
            couponPrice = marketCoupon.getDiscount();
        }
        MarketOrder marketOrder = new MarketOrder();
        // 设置订单编号
        Date date = new Date();
        String dateSn = new SimpleDateFormat("yyyyMMdd").format(date);
        String orderSn = dateSn + getRandom(6);
        // 订单编号：使用年月日时分秒
        marketOrder.setOrderSn(orderSn);
        marketOrder.setOrderStatus(Short.valueOf("201"));
        // 用户积分 直接写死为0
        BigDecimal integeralPrice = BigDecimal.ZERO;
        BigDecimal orderPrice = (goodsPrice.add(freightPrice)).subtract(couponPrice);
        BigDecimal actualPrice = orderPrice.subtract(integeralPrice);

        //收货人
        marketOrder.setConsignee(consignee);
        marketOrder.setMobile(mobile);
        marketOrder.setAddress(address);
        marketOrder.setMessage(submitOrderBo.getMessage());
        marketOrder.setGoodsPrice(goodsPrice);
        marketOrder.setFreightPrice(freightPrice);
        marketOrder.setCouponPrice(couponPrice);
        marketOrder.setIntegralPrice(integeralPrice);
        marketOrder.setOrderPrice(orderPrice);
        marketOrder.setActualPrice(actualPrice);
        marketOrder.setPayTime(date);
        // 以下会注释掉
        // 微信付款编号
        //marketOrder.setPayId(payId);
        // marketOrder.setGrouponPrice(grouponPrice);
        // marketOrder.setShipSn(shipSn);
        // marketOrder.setShipChannel(shipChannel);
        // marketOrder.setRefundAmount(refundAmount);
        // marketOrder.setRefundType(refundType);
        // marketOrder.setRefundContent(refundContent);
        // marketOrder.setRefundTime(refundtime);
        // marketOrder.setComments(comments);
        // marketOrder.setEndTime(endTime);
        //
        marketOrder.setGrouponPrice(BigDecimal.ZERO);
        marketOrder.setDeleted(false);
        marketOrder.setAddTime(date);
        marketOrder.setUpdateTime(date);
        marketOrder.setUserId(userId);
        // 向订单商品表插入数据,遍历
        int comments = 0;
        orderMapper.insertSelective(marketOrder);
        for (MarketCart marketCart : marketCarts) {
            // 获取商品数量
            Short number = marketCart.getNumber();
            comments = comments + number;
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            marketOrderGoods.setOrderId(marketOrder.getId());
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());
            marketOrderGoods.setGoodsName(marketCart.getGoodsName());
            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
            marketOrderGoods.setProductId(marketCart.getProductId());
            marketOrderGoods.setNumber(marketCart.getNumber());
            marketOrderGoods.setPrice(marketCart.getPrice());
            marketOrderGoods.setSpecifications(marketCart.getSpecifications());
            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
            marketOrderGoods.setComment(0);
            marketOrderGoods.setAddTime(marketOrder.getAddTime());
            marketOrderGoods.setUpdateTime(marketOrder.getUpdateTime());
            marketOrderGoods.setDeleted(marketOrder.getDeleted());
            orderGoodsMapper.insertSelective(marketOrderGoods);
        }
        MarketOrder updateOrderComments = new MarketOrder();
        updateOrderComments.setComments((short) comments);
        updateOrderComments.setId(marketOrder.getId());
        orderMapper.updateByPrimaryKeySelective(updateOrderComments);
        return marketOrder;



    }

    private String getRandom(int len) {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            stringBuffer.append(random.nextInt(10));
        }
        return stringBuffer.toString();
    }

    // 被弃用的方法（未写完）
    private List<WxOrderGoodsOfWxOrderDetailVo> getWxOrderGoodsInfoInWxOrderDetail(List<MarketOrderGoods> marketOrderGoods) {
        LinkedList<WxOrderGoodsOfWxOrderDetailVo> wxOrderGoodsOfWxOrderDetailVos = new LinkedList<>();
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            // 订单商品表id
            Integer id = marketOrderGood.getId();
            // 订单id
            Integer orderId = marketOrderGood.getOrderId();
            // 商品id
            Integer goodsId = marketOrderGood.getGoodsId();
            // 商品名称
            String goodsName = marketOrderGood.getGoodsName();
            // 商品编号
            String goodsSn = marketOrderGood.getGoodsSn();
            // 商品货品表的货品id
            Integer productId = marketOrderGood.getProductId();
            WxOrderGoodsOfWxOrderDetailVo wxOrderGoodsInfo = new WxOrderGoodsOfWxOrderDetailVo();
        }
        return wxOrderGoodsOfWxOrderDetailVos;
    }

    private WxOrderInfoOfWxOrderDetailVo getOrderInfo(MarketOrder marketOrder) {

        // 快递公司编号--expName,expCode
        String shipChannel = marketOrder.getShipChannel();
        String expName = Constant.ORDER_SHIP_NAME.get(shipChannel);
        // 收货人名称
        String consignee = marketOrder.getConsignee();
        // 地址
        String address = marketOrder.getAddress();
        // 添加时间
        Date addTime = marketOrder.getAddTime();
        // 订单号
        String orderSn = marketOrder.getOrderSn();
        // 实付费用
        BigDecimal actualPrice = marketOrder.getActualPrice();
        // 手机号
        String mobile = marketOrder.getMobile();
        // 留言
        String message = marketOrder.getMessage();
        // 订单状态
        Short orderStatus = marketOrder.getOrderStatus();
        String orderStatusText = Constant.ORDER_STATUS_TEXT.get(orderStatus.intValue());
        // 售后状态
        Short aftersaleStatus = marketOrder.getAftersaleStatus();
        // 商品总费用--goodsPrice
        BigDecimal goodsPrice = marketOrder.getGoodsPrice();
        // 发货编号
        String expNo = marketOrder.getShipSn();
        // 优惠劵减免金额
        BigDecimal couponPrice = marketOrder.getCouponPrice();
        // 订单id
        Integer id = marketOrder.getId();
        // 配送费用
        BigDecimal freightPrice = marketOrder.getFreightPrice();
        // 获取handleOption
        HandleOption handleOption = getHandleOption(marketOrder);

        return new WxOrderInfoOfWxOrderDetailVo(expName, consignee, address, addTime, orderSn, actualPrice, mobile, message, shipChannel, orderStatusText, aftersaleStatus, goodsPrice, expNo, couponPrice, id, freightPrice, handleOption);
    }

    private LinkedList<WxOrderListVo> getOrders(List<MarketOrder> marketOrders) {
        LinkedList<WxOrderListVo> wxOrderListVos = new LinkedList<>();
        for (MarketOrder marketOrder : marketOrders) {
            WxOrderListVo wxOrderListVo = new WxOrderListVo();
            wxOrderListVo.setActualPrice(marketOrder.getActualPrice());
            wxOrderListVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            wxOrderListVo.setId(marketOrder.getId());
            wxOrderListVo.setOrderSn(marketOrder.getOrderSn());
            if (marketOrder.getGrouponPrice() != null && marketOrder.getGrouponPrice().compareTo(BigDecimal.ZERO) == 1) {
                wxOrderListVo.setIsGroupin(true);
            } else {
                wxOrderListVo.setIsGroupin(false);
            }
            Short orderStatus = marketOrder.getOrderStatus();
            // 获取handleOption
            // handleOption 是用户的操作，有取消，删除，已付款，评论，确认收货，退款，重复购买，申请售后操作
            HandleOption handleOption = getHandleOption(marketOrder);
            wxOrderListVo.setOrderStatusText(Constant.ORDER_STATUS_TEXT.get(orderStatus.intValue()));
            // 封装goodsList,用的是OrderGoods接收数据库中的数据，如果不行，在采用封装后的
            List<MarketOrderGoods> goodsLists = getGoodsList(marketOrder.getId());
            wxOrderListVo.setGoodsList(goodsLists);
            wxOrderListVo.setHandleOption(handleOption);
            if (!marketOrder.getDeleted()) {
                wxOrderListVos.add(wxOrderListVo);
            }
        }
        return wxOrderListVos;
    }

    private HandleOption getHandleOption(MarketOrder marketOrder) {
        // handleOption 是用户的操作，有取消，删除，已付款，评论，确认收货，退款，重复购买，申请售后操作
        Short orderStatus = marketOrder.getOrderStatus();
        HandleOption handleOption = new HandleOption();
        if (orderStatus == 101) {
            handleOption.setCancel(true);
            handleOption.setPay(true);
        } else if (orderStatus == 201) {
            handleOption.setRefund(true);
        } else if (orderStatus == 301) {
            handleOption.setConfirm(true);
        } else if (!marketOrder.getDeleted() && (orderStatus == 401 || orderStatus == 402)) {
            handleOption.setDelete(true);
        }
        if ((marketOrder.getAftersaleStatus() == 0) && (orderStatus == 401 || orderStatus == 402)) {
            handleOption.setAftersale(true);
        }
        if ((marketOrder.getComments() > 0) && (orderStatus == 401)){
            // 可以评论
            handleOption.setComment(true);
        }
        if (orderStatus == 401 || orderStatus == 402) {
            // todo
            // 重复购买
            handleOption.setRebuy(true);
        }
        return handleOption;
    }

    private List<MarketOrderGoods> getGoodsList(Integer id) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(id);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
        return marketOrderGoods;

    }
    // 小程序用户登录后我的订单处数据显示
    @Override
    public UserIndexVo index () {
        // 获取当前登录用户信息
        Integer userId = ShiroUtil.getUserId();
        if (userId == null){
            return null;
        }
        // 查询四种状态对应的id，101、201、301、401
        int unpaid = orderMapper.countStatusByIdAndStatus(userId, 101);
        int unship = orderMapper.countStatusByIdAndStatus(userId, 201);
        int unrecv = orderMapper.countStatusByIdAndStatus(userId, 301);
        int uncomment = orderMapper.countStatusByIdAndStatus(userId, 401);
        UserIndexVo userIndexVo = new UserIndexVo(unpaid, unship, unrecv, uncomment);
        return userIndexVo;
    }

    @Override
    @Transactional
    public void wxRefundOrder(Integer userId, Integer orderId) {
        // 获取相关数据
        MarketOrder marketOrderBeforeUpdate = orderMapper.selectByPrimaryKey(orderId);
        BigDecimal actualPrice = marketOrderBeforeUpdate.getActualPrice();

        MarketOrder marketOrder = new MarketOrder();
        Date updateTime = new Date();
        marketOrder.setUpdateTime(updateTime);
        // 202 申请退款
        marketOrder.setOrderStatus(Short.valueOf("202"));
        // 1：用户已申请
        marketOrder.setAftersaleStatus(Short.valueOf("1"));
        marketOrder.setRefundAmount(actualPrice);
        marketOrder.setRefundType("微信付款接口");
        marketOrder.setUserId(userId);
        marketOrder.setId(orderId);
        //marketOrder.setRefundContent(refundContent);
        // marketOrder.setRefundTime(updateTime);
        // marketOrder.setEndTime(updateTime);
        orderMapper.updateByPrimaryKeySelective(marketOrder);

    }

    @Override
    public void wxCancelOrder(Integer orderId, Integer userId) {
        MarketOrder marketOrder = new MarketOrder();
        Date date = new Date();
        marketOrder.setUpdateTime(date);
        // 添加修改的数据, 修改订单状态 102：用户取消
        marketOrder.setOrderStatus(Short.valueOf("102"));
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    // 用户收货功能
    @Override
    public void wxConfirmOrder(Integer orderId, Integer userId) {
        MarketOrder marketOrder = new MarketOrder();
        Date date = new Date();
        marketOrder.setUpdateTime(date);
        marketOrder.setConfirmTime(date);
        // 添加修改的数据, 修改订单状态 401：用户取消
        marketOrder.setOrderStatus(Short.valueOf("401"));
        marketOrder.setId(orderId);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public MarketOrderGoods getOrderGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        if (orderId != null || orderId > 0) {
            criteria.andOrderIdEqualTo(orderId);
        }
        if (goodsId != null || goodsId > 0) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
        if (marketOrderGoods.size() == 0) {
            return null;
        }
        return marketOrderGoods.get(0);
    }

    @Override
    @Transactional
    public void wxOrderComment(OrderCommentBo orderCommentBo) {
        // 插入评论表中，并获取自增ID
        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(orderCommentBo.getOrderGoodsId());
        marketComment.setContent(orderCommentBo.getContent());
        marketComment.setStar(orderCommentBo.getStar());
        marketComment.setHasPicture(orderCommentBo.getHasPicture());
        marketComment.setPicUrls(orderCommentBo.getPicUrls());
        // 商品评论
        marketComment.setType(Byte.valueOf("0"));
        commentMapper.insertSelective(marketComment);
        // 把评论自增id更新order_goods表中
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        // 更新update时间 order_goods表
        Date date = new Date();
        marketOrderGoods.setUpdateTime(date);
        marketOrderGoods.setComment(marketComment.getId());
        orderGoodsMapper.updateByPrimaryKeySelective(marketOrderGoods);
        // 修改待评价商品数量order表
        // 获取order_goods中的商品数量
        MarketOrderGoods orderGoodsById = orderGoodsMapper.selectByPrimaryKey(marketComment.getValueId());
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderGoodsById.getOrderId());
        // 未评价商品数量
        Short comments = marketOrder.getComments();
        // 商品数量（已评价）
        Short number = orderGoodsById.getNumber();
        int sub = 0;
        if (comments.compareTo(number) == 1) {
            sub = comments - number;
        }
        // 更新update时间和状态 order表
        MarketOrder marketOrderForUpdate = new MarketOrder();
        marketOrderForUpdate.setId(orderGoodsById.getOrderId());
        marketOrderForUpdate.setUpdateTime(date);
        marketOrderForUpdate.setOrderStatus(Short.valueOf("402"));
        marketOrderForUpdate.setComments(((short) sub));
        orderMapper.updateByPrimaryKeySelective(marketOrderForUpdate);
    }

    @Override
    public void replyComment(OrderCommentReplyBO replyBO) {
        MarketComment comment = commentMapper.selectByPrimaryKey(replyBO.getCommentId());
        comment.setAdminContent(replyBO.getContent());
        comment.setUpdateTime(new Date());
        commentMapper.updateByPrimaryKeySelective(comment);
    }

}
